In [62]:
from fastai.vision import *
In [63]:
classes = ['With-Mask','WithOut-Mask']
In [66]:
path=Path('storage/data/mask')
In [67]:
path.ls()
Out[67]:
[PosixPath('storage/data/mask/With-Mask'),
 PosixPath('storage/data/mask/Without-Mask')]
In [68]:
np.random.seed(42)
data = ImageDataBunch.from_folder(path, train='.', valid_pct=0.2,
        ds_tfms=get_transforms(), size=224, num_workers=4).normalize(imagenet_stats)
In [69]:
data.classes
Out[69]:
['With-Mask', 'Without-Mask']
In [70]:
data.show_batch(rows=3, figsize=(7,8))
In [71]:
data.classes, data.c, len(data.train_ds), len(data.valid_ds)
Out[71]:
(['With-Mask', 'Without-Mask'], 2, 1076, 269)
In [72]:
learn = cnn_learner(data, models.resnet34, metrics=error_rate)
In [73]:
learn.fit_one_cycle(2, max_lr=slice(3e-5,3e-4))
epoch train_loss valid_loss error_rate time
0 0.710087 0.082847 0.018587 00:09
1 0.385154 0.050825 0.014870 00:09
In [75]:
learn.lr_find()
71.43% [5/7 00:37<00:15]
epoch train_loss valid_loss error_rate time
0 0.423371 #na# 00:07
1 0.414845 #na# 00:07
2 0.476447 #na# 00:07
3 0.333211 #na# 00:07
4 0.281560 #na# 00:07

18.75% [3/16 00:02<00:09 0.4733]
LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.
In [76]:
learn.recorder.plot()
In [77]:
learn.fit_one_cycle(6, max_lr=slice(3e-2,3e-1))
epoch train_loss valid_loss error_rate time
0 0.260513 0.417052 0.040892 00:08
1 0.763670 11.902088 0.107807 00:08
2 1.623852 16.162880 0.122677 00:08
3 1.868275 1.492338 0.048327 00:09
4 1.554766 0.000000 0.000000 00:09
5 1.230582 0.000003 0.000000 00:09
In [79]:
learn.lr_find()
71.43% [5/7 00:37<00:14]
epoch train_loss valid_loss error_rate time
0 0.117950 #na# 00:07
1 0.122952 #na# 00:07
2 0.208999 #na# 00:07
3 0.151172 #na# 00:07
4 0.225113 #na# 00:07

25.00% [4/16 00:02<00:07 0.3499]
LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.
In [80]:
learn.recorder.plot(),
learn.recorder.plot_lr(show_moms=True)
In [81]:
learn.recorder.plot_losses()
In [82]:
learn.fit_one_cycle(4, max_lr=slice(3e-3,3e-2))
epoch train_loss valid_loss error_rate time
0 0.134067 0.000000 0.000000 00:09
1 0.201127 0.252006 0.003717 00:08
2 0.230596 0.082474 0.003717 00:08
3 0.142813 0.130116 0.003717 00:09
In [83]:
interp = ClassificationInterpretation.from_learner(learn)
In [84]:
interp.plot_confusion_matrix()
In [85]:
learn.export()
In [98]:
defaults.device = torch.device('cpu')
In [106]:
img = open_image(path/'3.jpg')
img
Out[106]:
In [107]:
learn = load_learner(path)
In [108]:
pred_class,pred_idx,outputs = learn.predict(img)
pred_class ,
Out[108]:
(Category Without-Mask,)
In [ ]: